package com.dzb.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码实现类
 */
public class VerifyCode {
    public static Random r=new Random();   //生成随机数
    public static String source="ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"abcdefghijklmnopqrstuvwxyz"+"0123456789";  //设定可能的字符
    public static char[] src=source.toCharArray();

    //产生随机字符串
    private static String randString(int length){
        char[] buf=new char[length];
        int rnd;
        for(int i=0;i<length;i++){
            rnd=Math.abs((r.nextInt())%src.length);
            buf[i]=src[rnd];
        }

        return new String(buf);
    }

    //调用该方法产生随机字符串，i为需要产生字符串长度
    public String runVerifyCode(int i){
        String VerifyCode=randString(i);
        return VerifyCode;
    }

    //给定范围获得随机颜色,传入前景色数值和背景色数值
    public Color getRandColor(int fc,int bc){
        Random random=new Random();
        if(fc>255){
            fc=255;
        }
        if(bc>255){
            bc=255;
        }
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }


    //调用该方法将得到的验证码生成图像
    //sCode：传递验证码 w：图像宽度  h：图像高度
    public BufferedImage CreateImage(String sCode) {
        try {
            Font CodeFont = new Font("Arial Black", Font.PLAIN, 16);
            int iLength = sCode.length();                //得到验证码长度
            int width = 22 * iLength, height = 30;          //设置图像的宽度和高度
            int CharWidth = (int) (width - 24) / iLength; //设置字符距左边宽度
            int CharHeight = 18;

            //在内存中创建图像
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();       //获得图形上下文
            Random random = new Random();
            g.setColor(this.getRandColor(200, 240));  //设定背景色
            g.fillRect(0, 0, width, height);
            g.setFont(CodeFont);      //设置字体
            g.setColor(this.getRandColor(10, 50));   //画随机颜色的边框
            g.drawRect(0, 0, width - 1, height - 1);

            //随机产生155条干扰线，使图形中的认证码不容易被其他程序探测到
            g.setColor(this.getRandColor(160, 200));
            for (int i = 0; i < 155; i++) {
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int x1 = random.nextInt(12);
                int y1 = random.nextInt(12);
                g.drawLine(x, y, x + x1, y + y1);
            }
            for (int i = 0; i < iLength; i++) {
                String rand = sCode.substring(i, i + 1);
                g.setColor(new Color(20 + random.nextInt(60), 20 + random.nextInt(120), 20 + random.nextInt(180))); //将认证码显示到图像中
                g.drawString(rand, CharWidth * i + 14, CharHeight);
            }

            g.dispose();  //图像生效
            return image;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
